package com.robaone.gwt.form.client.ui;

import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;

/**
   Copyright Mar 23, 2012 Ansel Robateau
   http://www.robaone.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 **/

/**
 * @author Ansel Robateau
 *
 */
public class FormSubmitCompleteHandler implements SubmitCompleteHandler {

	FormUi m_formui;
	
	public FormSubmitCompleteHandler(FormUi form){
		this.m_formui = form;
	}
	/* (non-Javadoc)
	 * @see com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler#onSubmitComplete(com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent)
	 */
	@Override
	public void onSubmitComplete(SubmitCompleteEvent event) {
		m_formui.getForm().setAction(m_formui.getAction());
		System.out.println("SubmitCompleteHandler()");
		String html = event.getResults();
		if(html == null){
			m_formui.addError("Invalid Response");
		}else{
			/**
			 * Parse response
			 */
			// if error then show errors
			if(!html.startsWith("{")){
				m_formui.addError("Invalid Response");
			}else{
				// parse json and create an object
				try{
					JSONValue jsonValue = JSONParser.parseLenient(html);
					m_formui.update(jsonValue);
				}catch(Exception e){
					m_formui.addError("Invalid Response");
				}
			}
		}
		m_formui.setSubmitting(false);
	}

}
